//
//  HFOpenGLCapturer.m
//  HocusFocus
//
//  Created by Juan Carlos Jimenez on 4/6/08.
//  Copyright 2008 Juan Carlos Jimenez. All rights reserved.
//
#import "HFOpenGLCapturer.h"
#import <CoreFoundation/CoreFoundation.h>
#import <ApplicationServices/ApplicationServices.h>
#import <QuartzCore/QuartzCore.h>
#import <OpenGL/OpenGL.h>
#import <OpenGL/gl.h>

static HFOpenGLCapturer *sharedInstance = nil;

@implementation HFOpenGLCapturer

+ (HFOpenGLCapturer *)sharedInstance
{
	if (sharedInstance == nil) {
		sharedInstance = [[HFOpenGLCapturer alloc] init];
	}
	return sharedInstance;
}

- (NSImage *)createImageFromCGImage:(CGImageRef)cgImage
{
    NSRect imageRect = NSMakeRect(0.0, 0.0, CGImageGetWidth(cgImage), CGImageGetHeight(cgImage));
    NSImage *result = [[[NSImage alloc] initWithSize:imageRect.size] autorelease];
	
	[result lockFocus];
    CGContextRef imageContext = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
    CGContextDrawImage(imageContext, *(CGRect *)&imageRect, cgImage);
    [result unlockFocus];
	
    return result;
}

- (NSImage *)captureImageRect:(NSRect)rect forScreenRect:(NSRect)screenRect
{
	NSImage *result;
    CGImageRef cgImage;
    
    rect.origin.y = screenRect.size.height - rect.origin.y - rect.size.height;
    cgImage = CGWindowListCreateImage(CGRectMake(rect.origin.x , rect.origin.y, rect.size.width, rect.size.height),
                                      kCGWindowListOptionAll,
                                      kCGNullWindowID,
                                      kCGWindowImageDefault);
    @try {
        // 10.6+ - this method might be faster
        result = [[[NSImage alloc] initWithCGImage:cgImage size:rect.size] autorelease];
        //result = [self createImageFromCGImage:cgImage];
    } @finally {
        CGImageRelease(cgImage);
    }
    return result;
}

@end
